package com.sure0000.timeServer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @program: demo
 * @description:
 * @author: xuyouchang@supcon.com
 * @create: 2019-11-04 13:47
 **/
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    // 连接建立时触发调用
    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        // 分配 buffer 空间
        final ByteBuf time = ctx.alloc().buffer(4);
        System.out.println("time server handler");
        time.writeInt((int) (System.currentTimeMillis()/1000L + 2208988800L));

        //  it has two pointers; one for read operations and the other for write
        //  operations.The writer index increases when you write something to a
        //  ByteBuf while the reader index does not change. The reader index and
        //  the writer index represents where the message starts and ends respectively.
        final ChannelFuture f = ctx.writeAndFlush(time);

        // all operations are asynchronous in Netty
        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                assert f == future;
                ctx.close();
            }
        });
    }
}
